package cn.tom.tompicturebackend.controller;

import cn.hutool.cache.Cache;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.json.JSONUtil;
import cn.tom.tompicturebackend.annotation.AuthCheck;

import cn.tom.tompicturebackend.api.imagesearch.ImageSearchApiFacade;
import cn.tom.tompicturebackend.api.imagesearch.model.ImageSearchResult;
import cn.tom.tompicturebackend.common.BaseResponse;
import cn.tom.tompicturebackend.common.DeleteRequest;
import cn.tom.tompicturebackend.common.ResultUtils;
import cn.tom.tompicturebackend.constant.UserConstant;
import cn.tom.tompicturebackend.exception.BusinessException;
import cn.tom.tompicturebackend.exception.ErrorCode;
import cn.tom.tompicturebackend.exception.ThrowUtils;
import cn.tom.tompicturebackend.model.dto.picture.*;
import cn.tom.tompicturebackend.model.entity.Picture;
import cn.tom.tompicturebackend.model.entity.Space;
import cn.tom.tompicturebackend.model.entity.User;
import cn.tom.tompicturebackend.model.enums.PictureReviewStatusEnum;
import cn.tom.tompicturebackend.model.vo.PictureVO;
import cn.tom.tompicturebackend.service.PictureService;
import cn.tom.tompicturebackend.service.SpaceService;
import cn.tom.tompicturebackend.service.UserService;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.benmanes.caffeine.cache.Caffeine;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

@RestController
public class PictureController {

    @Resource
    private UserService userService;

    @Resource
    private PictureService pictureService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private SpaceService spaceService;

    private final Cache<String,String> LOCAL_CACHE =
            (Cache<String, String>) Caffeine.newBuilder().initialCapacity(1024)
           .maximumSize(1000L)
           .expireAfterWrite(5L, TimeUnit.MINUTES)
           .build();


    /**
     * 上传图片
     */
    @PostMapping("/upload")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<PictureVO> uploadPicture(
            @RequestPart("file")MultipartFile multipartFile, PictureUploadRequest pictureUploadRequest,
            HttpServletRequest request
            )
    {
        User loinUser = userService.getLoinUser(request);
        PictureVO pictureVO = pictureService.uploadPicture(multipartFile, pictureUploadRequest, loinUser);
        return ResultUtils.success(pictureVO);

    }

    /**
     * 删除
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    public BaseResponse<Boolean> deletePicture(@RequestBody DeleteRequest deleteRequest,HttpServletRequest request)
    {
        if(deleteRequest == null || deleteRequest.getId() <= 0){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loinUser = userService.getLoinUser(request);
        long id = deleteRequest.getId();

        //判断是否存在
        Picture picture = pictureService.getById(id);
      //判断是否为管理员或本人
        if(!picture.getUserId().equals(loinUser.getId()) && !userService.isAdmin(loinUser)){
            throw new BusinessException(ErrorCode.NOT_AUTHORIZED_ERROR);
        }
        //删除
        boolean result = pictureService.removeById(id);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }
    /**
     * 更新
     */
    @PostMapping("/update")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> updatePicture(@RequestBody PictureUpdateRequest pictureUpdateRequest,HttpServletRequest request)
    {
        if(pictureUpdateRequest == null || pictureUpdateRequest.getId() <= 0){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        //将实体类 DTO 进行转换
        Picture picture = new Picture();
        BeanUtils.copyProperties(pictureUpdateRequest, picture);

        //注意将 list 转换String
        picture.setTags(JSONUtil.toJsonStr(pictureUpdateRequest.getTags()));
        //数据检验
        pictureService.validPicture(picture);
        //判断是否存在
        long id = pictureUpdateRequest.getId();
        Picture oldPicture = pictureService.getById(id);
        ThrowUtils.throwIf(oldPicture == null, ErrorCode.NOT_FOUND_ERROR);

        //补充审核参数
        User loinUser = userService.getLoinUser(request);
        pictureService.fillReviewParams(picture, loinUser);

        //操作数据库更新
        boolean result = pictureService.updateById(picture);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);

        return ResultUtils.success(true);
    }
    /**
     * 根据id 获取图表(仅管理员)
     */
    @GetMapping("/get")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Picture> getPictureById(long id,HttpServletRequest request)
    {
        ThrowUtils.throwIf(id <= 0, ErrorCode.PARAMS_ERROR);
        //查询数据库
        Picture picture = pictureService.getById(id);
        ThrowUtils.throwIf(picture == null, ErrorCode.NOT_FOUND_ERROR);
        //返回结果
        return ResultUtils.success(picture);
    }
    /**
     * 根据id 获取图片
     */
    @GetMapping("/get/vo")
    public BaseResponse<PictureVO> getPictureVOById(long id,HttpServletRequest request)
    {
        ThrowUtils.throwIf(id <= 0, ErrorCode.PARAMS_ERROR);
        //查询数据库
        Picture picture = pictureService.getById(id);

        ThrowUtils.throwIf(picture == null, ErrorCode.NOT_FOUND_ERROR);// 空间权限校验
        Long spaceId = picture.getSpaceId();
        if (spaceId != null) {
            User loginUser = userService.getLoginUser(request);
            pictureService.checkPictureAuth(loginUser, picture);
        }
        //返回结果
        return ResultUtils.success(pictureService.getPictureVO(picture,request));
    }

    /**
     * 分页获取图片列表(仅管理员)
     */
    @PostMapping("/list/page")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<Picture>> listPictureByPage(@RequestBody PictureQueryRequest pictureQueryRequest,HttpServletRequest request)
    {
        long current = pictureQueryRequest.getCurrent();
        long size = pictureQueryRequest.getPageSize();

        //限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);

        //普通用户默认只能查看过审核的数据
        pictureQueryRequest.setReviewStatus(PictureReviewStatusEnum.PASS.getValue());
        // 空间权限校验
        Long spaceId = pictureQueryRequest.getSpaceId();
// 公开图库
        if (spaceId == null) {
            // 普通用户默认只能查看已过审的公开数据
            pictureQueryRequest.setReviewStatus(PictureReviewStatusEnum.PASS.getValue());
            pictureQueryRequest.setNullSpaceId(true);
        } else {
            // 私有空间
            User loginUser = userService.getLoginUser(request);
            Space space = spaceService.getById(spaceId);
            ThrowUtils.throwIf(space == null, ErrorCode.NOT_FOUND_ERROR, "空间不存在");
            if (!loginUser.getId().equals(space.getUserId())) {
                throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "没有空间权限");
            }
        }


        //查询数据库
        Page<Picture> picturePage = pictureService.page(new Page<>(current, size), pictureService.getQueryWrapper(pictureQueryRequest));

        //获取封装类
        return ResultUtils.success(picturePage);


    }
    /**
     * 分页获取图片列表（封装类）
     *
     */
    @PostMapping("/list/page/vo")
    public BaseResponse<Page<PictureVO>> listPictureVOByPage(@RequestBody PictureQueryRequest pictureQueryRequest,HttpServletRequest request)
    {
        long current = pictureQueryRequest.getCurrent();
        long size = pictureQueryRequest.getPageSize();
        //限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        //查询数据库
        Page<Picture> picturePage = pictureService.page(new Page<>(current, size), pictureService.getQueryWrapper(pictureQueryRequest));

        return ResultUtils.success(pictureService.getPictureVOPage(picturePage,request));

    }
    /**
     * 编辑图片
     */
    @PostMapping("/edit")
    public BaseResponse<Boolean> editPicture(@RequestBody PictureEditRequest pictureEditRequest,HttpServletRequest request)
    {
        if (pictureEditRequest ==null || pictureEditRequest.getId() <= 0){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        //在此处将实体类DTO 转换为实体类PO
        Picture picture = new Picture();
        BeanUtils.copyProperties(pictureEditRequest,picture);

        //注意将list 转换 string
        picture.setTags(JSONUtil.toJsonStr(pictureEditRequest.getTags()));
        //设置编辑时间
        picture.setUpdateTime(new Date());

        //数据检验
        pictureService.validPicture(picture);
        User loinUser = userService.getLoinUser(request);

        //判断是否存在
        Long id = pictureEditRequest.getId();
        Picture oldPicture = pictureService.getById(id);

        ThrowUtils.throwIf(oldPicture == null, ErrorCode.NOT_FOUND_ERROR);
        //判断是否为管理员
        if(!oldPicture.getUserId().equals(loinUser.getId()) && !userService.isAdmin(loinUser)){
            throw new BusinessException(ErrorCode.NOT_AUTHORIZED_ERROR);
        }

        //补充审核参数
        pictureService.fillReviewParams(picture, loinUser);

        //操作数据库
        boolean result = pictureService.updateById(picture);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);


    }
    @GetMapping("/tag_category")
    public BaseResponse<PictureTagCategory> listPictureTagCategory()
    {

        PictureTagCategory pictureTagCategory = new PictureTagCategory();
        List<String> tagList = Arrays.asList("热门", "搞笑");
        List<String> categoryList = Arrays.asList("风景", "人物", "动物", "植物", "建筑", "美食", "科技", "艺术", "历史", "文化", "体育", "旅游", "生活", "自然", "教育", "军事", "财经", "娱乐", "时尚", "汽车", "房产", "健康", "旅游", "时尚", "汽车", "房产", "健康", "旅游");
        pictureTagCategory.setTagList(tagList);
        pictureTagCategory.setCategoryList(categoryList);
        return ResultUtils.success(pictureTagCategory);

    }

    @PostMapping("/review")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> doPictureReview(@RequestBody PictureReviewRequest pictureReviewRequest, HttpServletRequest request)
    {
        ThrowUtils.throwIf(pictureReviewRequest == null, ErrorCode.PARAMS_ERROR);
        User loinUser = userService.getLoinUser(request);
        pictureService.doPictureReview(pictureReviewRequest, loinUser);
        return ResultUtils.success(true);

    }

    @PostMapping("/list/page/vo/cache")
    public BaseResponse<Page<PictureVO>> listPictureVOByPageWithCache(@RequestBody PictureQueryRequest pictureQueryRequest,
                                                                      HttpServletRequest request)
    {
        long current = pictureQueryRequest.getCurrent();
        long size = pictureQueryRequest.getPageSize();

        //限制爬虫
        ThrowUtils.throwIf(current < 1 || size > 20, ErrorCode.PARAMS_ERROR);

        //普通用户默认只能查看过审的数据
        pictureQueryRequest.setReviewStatus(PictureReviewStatusEnum.PASS.getValue());

        //构建key
        String queryCondition = JSONUtil.toJsonStr(pictureQueryRequest);
        String hashKey = DigestUtils.md5DigestAsHex(queryCondition.getBytes());

        String  cacheKey = "tompicture:listPictureVOByPage:" + hashKey;

        //优化 一级 本地 二级 分布式 三级数据库
        // 1、查询本地缓存
        String cacheValue = LOCAL_CACHE.get(cacheKey);
        if (cacheValue != null) {
            Page<PictureVO> pictureVOPage = JSONUtil.toBean(cacheValue, Page.class);
            return ResultUtils.success(pictureVOPage);
        }

        // 2、从分布式中获取
        ValueOperations<String, String> valuesOps = stringRedisTemplate.opsForValue();

        cacheValue = valuesOps.get(cacheKey);

        if(cacheValue !=null){
            //如果缓存命中,返回结果，存入本地缓存并返回
            LOCAL_CACHE.put(cacheKey,cacheValue);
            Page<PictureVO> pictureVOPage = JSONUtil.toBean(cacheValue, Page.class);
            return ResultUtils.success(pictureVOPage);
        }

        //查看数据库
        Page<Picture> picturePage = pictureService.page(new Page<>(current, size), pictureService.getQueryWrapper(pictureQueryRequest));

        //获取封装类
        Page<PictureVO> pictureVOPage = pictureService.getPictureVOPage(picturePage, request);

        //更新缓存
        cacheValue = JSONUtil.toJsonStr(pictureVOPage);

        //更新本地缓存

        LOCAL_CACHE.put(cacheKey,cacheValue);
        // 5-10 分钟随机过期，防止雪崩
        int expireTime = 300 + RandomUtil.randomInt(0,300);
        valuesOps.set(cacheKey, cacheValue, expireTime, TimeUnit.SECONDS);

        return ResultUtils.success(pictureVOPage);

    }

    /**
     * 以图搜图
     */
    @PostMapping("/search/picture")
    public BaseResponse<List<ImageSearchResult>> searchPictureByPicture(@RequestBody SearchPictureByPictureRequest searchPictureByPictureRequest) {
        ThrowUtils.throwIf(searchPictureByPictureRequest == null, ErrorCode.PARAMS_ERROR);
        Long pictureId = searchPictureByPictureRequest.getPictureId();
        ThrowUtils.throwIf(pictureId == null || pictureId <=0, ErrorCode.PARAMS_ERROR);
        Picture oldPicture = pictureService.getById(pictureId);
        ThrowUtils.throwIf(oldPicture == null, ErrorCode.PARAMS_ERROR);
        List<ImageSearchResult> imageSearchResults = ImageSearchApiFacade.searchImage(oldPicture.getUrl());
        return ResultUtils.success(imageSearchResults);
    }

    @PostMapping("/edit/batch")
    public BaseResponse<Boolean> editPictureByBatch(@RequestBody PictureEditByBatchRequest pictureEditByBatchRequest, HttpServletRequest httpServletRequest) {
        ThrowUtils.throwIf(pictureEditByBatchRequest == null, ErrorCode.PARAMS_ERROR);
        User loninUser = userService.getLoinUser(httpServletRequest);
        pictureService.editPictureByBatch(pictureEditByBatchRequest, loninUser);
        return ResultUtils.success(true);
    }



}
